package com.pancoit.bdsdkdemo.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.pancoit.bdsdkdemo.R;
import com.pancoit.bdsdkdemo.adapter.AppFragmentPageAdapter;
import com.pancoit.bdsdkdemo.base.BaseActivity;
import com.pancoit.bdsdkdemo.base.BaseFragment;
import com.pancoit.bdsdkdemo.constant.Constant;
import com.pancoit.bdsdkdemo.constant.GlobalParams;
import com.pancoit.bdsdkdemo.constant.TerminalParams;
import com.pancoit.bdsdkdemo.fragment.CommandFragment;
import com.pancoit.bdsdkdemo.fragment.CommunicationFragment;
import com.pancoit.bdsdkdemo.fragment.OtherFragment;
import com.pancoit.bdsdkdemo.fragment.StatusFragment;
import com.pancoit.bdsdkdemo.utils.PreferencesUtils;
import com.pancoit.bdsdkdemo.view.BluetoothDialog;
import com.pancoit.bdsdkdemo.view.CommandSettingDialog;
import com.pancoit.bdsdkdemo.view.FragmentViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    //Fragment容器
    @BindView(R.id.container_vp)
    FragmentViewPager containerVp;
    //切换到状态页按钮
    @BindView(R.id.status_layout)
    LinearLayout statusLayout;
    //通信页
    @BindView(R.id.communication_layout)
    LinearLayout communicationLayout;
    //指令页
    @BindView(R.id.command_layout)
    LinearLayout commandLayout;
    //其他页面
    @BindView(R.id.other_layout)
    LinearLayout otherLayout;
    //底部切换栏
    @BindView(R.id.bottom_bar_layout)
    LinearLayout bottomBarLayout;
    //
    @BindView(R.id.tab_status_img)
    ImageView tabStatusImg;
    //
    @BindView(R.id.tab_status_tv)
    TextView tabStatusTv;
    //
    @BindView(R.id.tab_communication_img)
    ImageView tabCommunicationImg;
    //
    @BindView(R.id.tab_communication_tv)
    TextView tabCommunicationTv;
    //
    @BindView(R.id.tab_command_tv)
    TextView tabCommandTv;
    //
    @BindView(R.id.tab_command_img)
    ImageView tabCommandImg;
    //
    @BindView(R.id.tab_other_img)
    ImageView tabOtherImg;
    //
    @BindView(R.id.tab_other_tv)
    TextView tabOtherTv;

    /*******************************************(只是单纯的强迫症想分割一下)******************************************************/
    private boolean isRefreshing = false;
    //权限请求码
    private final int mRequestCode = 0;
    //需要申请的权限
    private String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    //未申请成功的权限
    private List<String> mPermissionList = new ArrayList<>();
    //所有权限是否请求成功
    private boolean isPermissionsRequestSuccess = false;
    //页面列表
    private List<BaseFragment> mFragmentPages;
    //底部页面切换按钮
    private List<LinearLayout> mPageIndicates;
    //蓝牙连接弹框
    private BluetoothDialog bluetoothDialog;
    //设置按钮
    private ImageView settimgImg;
    //指令页面设置弹框
    private CommandSettingDialog commandSettingDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        initTitleBar(false, getActivity().getResources().getString(R.string.status));
        settimgImg = findViewById(R.id.setting_img);
        initFragment();
    }

    @Override
    protected void initEvent() {
        containerVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageChanged(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void initData() {
        GlobalParams.selfCheckingFrequency = PreferencesUtils.getInt(Constant.selfCheckingFrequency);
        GlobalParams.outputFormat = PreferencesUtils.getInt(Constant.outputFormat);
        requestLocationPermissions();
    }


    /*******************************************(权限管理)******************************************************/

    /**
     * 申请权限
     */
    private void requestLocationPermissions() {
        //清空没有通过的权限
        mPermissionList.clear();
        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {
            //有权限没有通过，需要申请
            ActivityCompat.requestPermissions(this, permissions, mRequestCode);
        } else {
            isPermissionsRequestSuccess = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (mRequestCode == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            if (hasPermissionDismiss) {
                //有权限没有被允许
                Log.i("InfoMessage", "请给予相关的权限，否则蓝牙功能将不能正常使用");
            } else {
                isPermissionsRequestSuccess = true;
            }
        }
    }

    /**
     * 初始化页面
     */
    private void initFragment() {
        //添加底部按钮
        mPageIndicates = new ArrayList<>();
        mPageIndicates.add(statusLayout);
        mPageIndicates.add(communicationLayout);
        mPageIndicates.add(commandLayout);
        mPageIndicates.add(otherLayout);
        //添加页面
        mFragmentPages = new ArrayList<>();
        mFragmentPages.add(new StatusFragment());
        mFragmentPages.add(new CommunicationFragment());
        mFragmentPages.add(new CommandFragment());
        mFragmentPages.add(new OtherFragment());
        //设置容器最大值
        containerVp.setOffscreenPageLimit(mFragmentPages.size());
        AppFragmentPageAdapter adapter = new AppFragmentPageAdapter(getSupportFragmentManager(), AppFragmentPageAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mFragmentPages);
        containerVp.setAdapter(adapter);

       /* changePage(0);
        pageChanged(0);*/
    }

    /**
     * ViewPage页面滚动切换的回调
     *
     * @param position 滚动后的页面索引
     */
    private void pageChanged(int position) {
        for (int i = 0; i < mPageIndicates.size(); i++) {
            if (position == i) {
                changeTabItemToChecked(i);
                mFragmentPages.get(i).onShow();
            } else {
                changeTabItemToUnChecked(i);
                mFragmentPages.get(i).onHide();
            }
        }
        getWindow().getDecorView().postDelayed(() -> hideInputKeybord(), 200);
    }

    /**
     * 选中状态
     *
     * @param position
     */
    private void changeTabItemToChecked(int position) {
        if (position == 0) {
            initTitleBar(false, getActivity().getResources().getString(R.string.status));
            settimgImg.setVisibility(View.GONE);
            tabStatusImg.setBackgroundResource(R.mipmap.status_check_icon);
            tabStatusTv.setTextColor(getActivity().getResources().getColor(R.color.colorPrimary));
        } else if (position == 1) {
            initTitleBar(false, getActivity().getResources().getString(R.string.communication));
            settimgImg.setVisibility(View.GONE);
            tabCommunicationImg.setBackgroundResource(R.mipmap.communication_check_icon);
            tabCommunicationTv.setTextColor(getActivity().getResources().getColor(R.color.colorPrimary));
        } else if (position == 2) {
            initTitleBar(false, getActivity().getResources().getString(R.string.command));
            settimgImg.setVisibility(View.VISIBLE);
            tabCommandImg.setBackgroundResource(R.mipmap.command_check_icon);
            tabCommandTv.setTextColor(getActivity().getResources().getColor(R.color.colorPrimary));
        } else if (position == 3) {
            initTitleBar(false, getActivity().getResources().getString(R.string.other));
            settimgImg.setVisibility(View.GONE);
            tabOtherImg.setBackgroundResource(R.mipmap.other_check_icon);
            tabOtherTv.setTextColor(getActivity().getResources().getColor(R.color.colorPrimary));
        }
    }

    /**
     * 未选中状态
     *
     * @param position
     */
    private void changeTabItemToUnChecked(int position) {
        if (position == 0) {
            tabStatusImg.setBackgroundResource(R.mipmap.status_uncheck_icon);
            tabStatusTv.setTextColor(getActivity().getResources().getColor(R.color.colorTextGray));
        } else if (position == 1) {
            tabCommunicationImg.setBackgroundResource(R.mipmap.communication_uncheck_icon);
            tabCommunicationTv.setTextColor(getActivity().getResources().getColor(R.color.colorTextGray));
        } else if (position == 2) {
            tabCommandImg.setBackgroundResource(R.mipmap.command_uncheck_icon);
            tabCommandTv.setTextColor(getActivity().getResources().getColor(R.color.colorTextGray));
        } else if (position == 3) {
            tabOtherImg.setBackgroundResource(R.mipmap.other_uncheck_icon);
            tabOtherTv.setTextColor(getActivity().getResources().getColor(R.color.colorTextGray));
        }
    }

    /**
     * 顶部TAB导航切换ViewPage页面主动调用
     *
     * @param position 目标页面索引
     */
    public void changePage(int position) {
        if (containerVp.getCurrentItem() == position || position < 0 || position >= mFragmentPages.size()) {
            return;
        }
        containerVp.setCurrentItem(position, true);
    }

    /**
     * 显示蓝牙弹框
     */
    public void showBluetoothDialog() {
        //判断是否申请权限成功
        if (!isPermissionsRequestSuccess) {
            requestLocationPermissions();
            return;
        }
        //判断是否打开了蓝牙
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            BluetoothAdapter.getDefaultAdapter().enable();
            return;
        }
        //判断盒子是否正常连接了
        if (TerminalParams.isConnectNormal) {
            return;
        }
        bluetoothDialog = new BluetoothDialog();
        if (bluetoothDialog.isAdded()) return;
        bluetoothDialog.setData(getActivity());
        bluetoothDialog.show(getFragmentManager(), "");
    }

    /**
     * 显示指令设置弹框
     */
    private void showCommandSettingDialog() {
        commandSettingDialog = new CommandSettingDialog();
        if (commandSettingDialog.isAdded()) {
            return;
        }
        commandSettingDialog.show(getFragmentManager(), "");
    }

    /**
     * 隐藏蓝牙对话框
     */
    public void hideBluetoothDialog() {
        if (bluetoothDialog != null) {
            bluetoothDialog.dismiss();
        }
    }

    @OnClick({R.id.status_layout, R.id.communication_layout, R.id.command_layout, R.id.other_layout, R.id.setting_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.status_layout:
                changePage(0);
                break;
            case R.id.communication_layout:
                changePage(1);
                break;
            case R.id.command_layout:
                changePage(2);
                break;
            case R.id.other_layout:
                changePage(3);
                break;
            case R.id.setting_img:
                showCommandSettingDialog();
                break;
        }
    }
}
